<?php
/**
 * 相关捆绑商品的处理
 *
 * @author chenping<chenping@shopex.cn>
 */

class inventorydepth_stock_pkg {

    public static $pkg = array();

    public static $pbn = array();
    
    public static $branch_products = array();
    
    public static $branches = array();

    public static $tmp_branch_pd = array();
    
    function __construct($app)
    {
        $this->app = $app;
        base_kvstore::config_persistent(false);
    }
    
    public function set_branch_products($branch_products)
    {
        self::$branch_products = $branch_products;
    }
    
    public function set_branches($branches)
    {
        self::$branches = $branches;
    }

    public function setPkg($pkg) 
    {
        self::$pkg = $pkg;
    }

    public function setPbn($pbn) 
    {
        self::$pbn = $pbn;
    }

    /**
     * @description 捆绑商品写进内存
     * @access public 
     * @param String $pkg_bn 捆绑商品货号
     * @param Array $data  捆绑商品信息
     * @return void
     */
    public function store_pkg($pkg_bn,$data) 
    {
        base_kvstore::instance('inventorydepth/local/pkg')->store($pkg_bn,$data);
    }

    /**
     * @description 从内存中读
     * @access public
     * @param String $pkg_bn 捆绑商品货号
     * @return Array $data  捆绑商品信息
     */
    public function fetch_pkg($pkg_bn) 
    {
        if(isset(self::$pkg[$pkg_bn])) return self::$pkg[$pkg_bn];
        
        $salesMaterialObj = app::get('material')->model('sales_material');#销售物料 ExBOY
        $salesMLib = kernel::single('material_sales_material');
        
        #获取对应的销售物料 ExBOY
        $pkgGood    = $salesMaterialObj->dump(array('sales_material_bn'=>$pkg_bn, 'sales_material_type'=>2), 'sm_id,sales_material_name,sales_material_bn,shop_id');
        
        #获取销售物料对应的基础物料
        if ($pkgGood)
        {
            $pkgProduct    = $salesMLib->getBasicMBySalesMId($pkgGood['sm_id']);
            $pkgGood['products'] = $pkgProduct;
        }
        
        self::$pkg[$pkg_bn] = $pkgGood;

        return self::$pkg[$pkg_bn] ;
    }

     /**
     * @description 删除捆绑商品
     * @access public
     * @param void
     * @return void
     */
    public function delete_pkg($pkg_bn) 
    {
        base_kvstore::instance('inventorydepth/local/pkg')->delete($pkg_bn);
    }

    public function store_pkg_products($pbn,$data) 
    {
        base_kvstore::instance('inventorydepth/local/pkg/products')->store($pbn,$data);
    }

    /**
     * @description 初始化
     * @access public
     * @param void
     * @return void
     */
    public function init() 
    {
        $pkg = array();

        /*
        $pkgGoodModel = app::get('omepkg')->model('pkg_goods');
        $pkgProductModel = app::get('omepkg')->model('pkg_product');
        $offset = 0 ; $limit = 400;
        do {
            $pgkGoods = $pkgGoodModel->getList('*',array(),$offset,$limit);
            if (!$pgkGoods) break;
            
            foreach ($pgkGoods as $key=>$value) {
                $pgkGoods[$key]['products'] = &$products[$value['goods_id']];

                $pp[$value['goods_id']] = $value['pkg_bn'];
            }
            
            $productList = $pkgProductModel->getList('bn,goods_id',array('goods_id'=>array_keys($products)));
            foreach ($productList as $key=>$value) {
                $products[$value['goods_id']][] = $value['bn'];
            }
            unset($productList);
            
            
            foreach ($pgkGoods as $key=>$value) {
                $this->store_pkg($value['pkg_bn'],$value);
            }

            $offset += $limit;
        }while(true);
        */
        
        $salesMaterialObj = app::get('material')->model('sales_material');#销售物料 ExBOY
        $salesMLib = kernel::single('material_sales_material');
        
        $offset = 0 ; $limit = 400;
        do {
            $pgkGoods    = $salesMaterialObj->getList('sm_id,sales_material_name,sales_material_bn,shop_id', array('sales_material_type'=>2),$offset,$limit);
            if (!$pgkGoods) break;
            
            foreach ($pgkGoods as $key=>$value) {
                $pgkGoods[$key]['products'] = &$products[$value['sm_id']];

                $pp[$value['sm_id']] = $value['sales_material_bn'];
            }
            
            $productList = $salesMLib->getBasicMBySalesMIds(array_keys($products));
            foreach ($productList as $sm_key=>$value) {
                
                foreach ($value as $bm_key => $bm_val)
                {
                    $products[$sm_key][] = $bm_val['material_bn'];
                }
            }
            unset($productList);
            
            
            foreach ($pgkGoods as $key=>$value) {
                $this->store_pkg($value['sales_material_bn'],$value);
            }

            $offset += $limit;
        }while(true);
    }

    public function pre_recycle($rows){
        foreach ($rows as $key=>$value) {
            $this->delete_pkg($value['sales_material_bn']);
        }
    }

    /**
     * @description 保存后续操作
     * @access public
     * @param Int $goods_id 捆绑商品ID
     */
    public function after_upsert($goods_id) 
    {
        /*
        $pkgGoodModel = app::get('omepkg')->model('pkg_goods');
        $pkgProductModel = app::get('omepkg')->model('pkg_product');

        $pgkGoods = $pkgGoodModel->getList('*',array('goods_id'=>$goods_id),0,1);

        $pkgProducts = $pkgProductModel->getList('bn',array('goods_id'=>$goods_id));

        $pgkGoods[0]['products'] = array_map('current',$pkgProducts);

        $this->store_pkg($pgkGoods[0]['pkg_bn'],$pgkGoods[0]);
        */
        
        $salesMaterialObj = app::get('material')->model('sales_material');#销售物料 ExBOY
        $salesMLib = kernel::single('material_sales_material');
        
        $pgkGoods    = $salesMaterialObj->getList('sm_id,sales_material_name,sales_material_bn,shop_id',array('sm_id'=>$goods_id, 'sales_material_type'=>2),0,1);
        
        $pkgProducts    = array();
        $product_list   = $salesMLib->getBasicMBySalesMId($goods_id);
        foreach ($product_list as $key=>$value) {
            $pkgProducts[]['material_bn'] = $value['material_bn'];
        }
        
        $pgkGoods[0]['products'] = array_map('current',$pkgProducts);
        
        $this->store_pkg($pgkGoods[0]['sales_material_bn'],$pgkGoods[0]);
    }

    /**
     * @description 涉及到修改的捆绑商品
     * @access public
     * @param void
     * @return void
     */
    public function writeMemory($products = array()) 
    {
        $salesMaterialObj = app::get('material')->model('sales_material');#销售物料 ExBOY
        $salesMLib = kernel::single('material_sales_material');
        
        $product_id = $pkgGood = array();
        foreach ($products as $key=>$value) {
            $tmpGoodsId[] = $value['sm_id'];
            $pkgGood[$value['sales_material_bn']] = $value;
            $pkgGood[$value['sales_material_bn']]['products'] = &$pkgp[$value['sm_id']];
        }
        
        #获取销售物料对应的基础物料明细
        $product_ids = array();
        $pkgProduct = $salesMLib->getBasicMBySalesMIds($tmpGoodsId);
        foreach ($pkgProduct as $key=>$value)
        {
            $pkgp[$key]    = $value;
        }

        $branches = app::get('ome')->model('branch')->select()->columns('branch_id,branch_bn,attr')->instance()->fetch_all();
        foreach ($branches as $key=>$branch) {
            self::$branches[$branch['branch_bn']] = $branch;
            $branch_ids[$branch['branch_id']] = $branch['branch_bn'];
        }
        
        $branchLib = kernel::single('ome_branch');
        $channelLib = kernel::single('channel_func');
        $basicMStorageLifeLib = kernel::single('material_storagelife');
        
        # 仓库货品
        $bpModel = app::get('ome')->model('branch_product');
        foreach($pkgGood as $pk =>$pg){
            foreach($pg['products'] as $product){
                if(self::$tmp_branch_pd[$product['bm_id']]){
                    $branch_products = self::$tmp_branch_pd[$product['bm_id']];
                }else{
                    $branch_products = $bpModel->getList('*',array('product_id'=>$product['bm_id']));
                    self::$tmp_branch_pd[$product['bm_id']] = $branch_products;
                }

                foreach ($branch_products as $key=>$bp) {
                    $branch_bn = $branch_ids[$bp['branch_id']];
                    
                    #识别物料是否保质期物料，是否自有仓储，获取失效的仓库物料库存数，和原总库存做减法
                    $branch_id    = $bp['branch_id'];
                    $product_id   = $bp['product_id'];
                    $wms_id = $branchLib->getWmsIdById($branch_id);
                    if($wms_id){
                        //是否自有仓储
                        $is_selfWms = $channelLib->isSelfWms($wms_id);
                        if($is_selfWms){
                            //是否保质期物料
                            $is_use_expire = $basicMStorageLifeLib->checkStorageLifeById($product_id);
                            if($is_use_expire){
                                $expire_store = $basicMStorageLifeLib->getExpireStorageLifeStore($branch_id, $product_id);
                                if($expire_store){
                                    $bp['store'] = $bp['store'] - $expire_store;
                                }
                            }
                        }
                    }
                    
                    self::$branch_products[$branch_bn][$pg['sales_material_bn']][$product['material_bn']] = $bp;
                }
            }
        }
        
        self::$pkg = $pkgGood;

        $this->batch = true;
    }

    public function resetVar() 
    {
        self::$pkg = array();
        $this->batch = false;
        return $this;
    }

    /**
     * 从内存中读仓库对应货品关系[促销销售物料_对应_基础物料库存]
     *
     * @return void
     * @author
     **/
    public function fetch_pkg_branch_products($branch_bn, $sales_material_bn, $material_bn)
    {
        if (self::$branch_products[$branch_bn][$sales_material_bn][$material_bn]) {
            return self::$branch_products[$branch_bn][$sales_material_bn][$material_bn];
        }
        
        if ($this->batch) { return false; }
        
        $branch = $this->fetch_branch($branch_bn);
        
        $branch_id = $branch['branch_id'];
        
        $product = $this->fetch_pkg($sales_material_bn);
        $sm_ids = $product['sm_id'];
        
        #获取销售物料对应的基础物料明细
        $product_id    = '';
        $basicMaterialObj = app::get('material')->model('basic_material');
        $get_basic_material    = $basicMaterialObj->dump(array('material_bn'=>$material_bn), 'bm_id');
        $product_id            = $get_basic_material['bm_id'];
        
        if(empty($get_basic_material))
        {
            return 0;
        }
        
        # 如果没有命中
        if (!$data)
        {
            if ($product_id && $branch_id) {
                #计算所有基础物料对应的仓库库存之和
                $oBranchProduct = app::get('ome')->model('branch_product');
                $field       = 'branch_id,product_id,store,store_freeze,last_modified,arrive_store,safe_store,is_locked';
                $dataList    = $oBranchProduct->getList($field, array('branch_id'=>$branch_id, 'product_id'=>$product_id));
                if($dataList){
                    $data = $dataList[0];

                    //识别物料是否保质期物料，是否自有仓储，获取失效的仓库物料库存数，和原总库存做减法
                    $branchLib = kernel::single('ome_branch');
                    $channelLib = kernel::single('channel_func');
                    $wms_id = $branchLib->getWmsIdById($branch_id);
                    if($wms_id){
                        //是否自有仓储
                        $is_selfWms = $channelLib->isSelfWms($wms_id);
                        if($is_selfWms){
                            //是否保质期物料
                            $basicMStorageLifeLib = kernel::single('material_storagelife');
                            $is_use_expire = $basicMStorageLifeLib->checkStorageLifeById($product_id);
                            if($is_use_expire){
                                $expire_store = $basicMStorageLifeLib->getExpireStorageLifeStore($branch_id, $product_id);
                                if($expire_store){
                                    $data['store'] = $data['store'] - $expire_store;
                                }
                            }
                        }
                    }

                }
            }
        }
        
        self::$branch_products[$branch_bn][$sales_material_bn][$material_bn] = $data;
        
        return $data;
    }
    
    /**
     * @description 读取仓库信息
     * @access public
     * @param void
     * @return void
     */
    public function fetch_branch($branch_bn)
    {
        if (self::$branches[$branch_bn]) {
            return self::$branches[$branch_bn];
        }
        
        if (!$data) {
            $data = app::get('ome')->model('branch')->select()->columns('branch_id,branch_bn')->where('branch_bn=?',$branch_bn)->instance()->fetch_row();
        }
    
        self::$branches[$branch_bn] = $data;
        return $data;
    }
}
